package com.yanqu.road.server.manger.activity.seacraft;

import com.yanqu.road.entity.activity.*;
import com.yanqu.road.entity.activity.seacraft.config.*;
import com.yanqu.road.entity.config.patrons.PatronsInfo;
import com.yanqu.road.entity.config.skill.SkillInfo;
import com.yanqu.road.entity.enums.*;
import com.yanqu.road.entity.player.UserInfo;
import com.yanqu.road.entity.player.UserPatrons;
import com.yanqu.road.entity.player.UserPatronsSkill;
import com.yanqu.road.entity.union.UnionBaseInfo;
import com.yanqu.road.entity.union.cross.CrossUnionInfo;
import com.yanqu.road.entity.union.UnionInfo;
import com.yanqu.road.entity.union.UnionMember;
import com.yanqu.road.logic.bussiness.activity.SeacraftSouthSeaBusiness;
import com.yanqu.road.logic.bussiness.player.UserPatronsBussiness;
import com.yanqu.road.logic.bussiness.servercenter.ActivityBussiness;
import com.yanqu.road.logic.helper.ActivityHelper;
import com.yanqu.road.logic.helper.UnionActivityGroupHelper;
import com.yanqu.road.logic.pb.UnionBasePb;
import com.yanqu.road.pb.activity.SeacraftSouthSeaProto;
import com.yanqu.road.pb.union.UnionProto;
import com.yanqu.road.server.TempMgr;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.activity.seacraft.SeacraftSouthSeaModule;
import com.yanqu.road.server.gameplayer.module.patrons.PatronsModule;
import com.yanqu.road.server.manger.SeacraftSouthSeaCommonMgr;
import com.yanqu.road.server.manger.ServerLanguageMgr;
import com.yanqu.road.server.manger.activity.ActivityMgr;
import com.yanqu.road.server.manger.activity.NormalActivityMgr;
import com.yanqu.road.server.manger.config.PatronsMgr;
import com.yanqu.road.server.manger.config.SkillMgr;
import com.yanqu.road.server.manger.config.SystemOpenMgr;
import com.yanqu.road.server.manger.player.GamePlayerMgr;
import com.yanqu.road.server.manger.union.CrossUnionMgr;
import com.yanqu.road.server.manger.union.GameUnionActivityGroupMgr;
import com.yanqu.road.server.protocol.CrossProtocol;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.utils.string.StringUtils;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Description 海上争霸 之 南海丝路
 * @Author cwq
 * @Data 2022/1/19 15:06
 */
public class SeacraftSouthSeaMgr extends TempMgr {

    private static ActivityInfo activityInfo;

    /**
     * 配置
     */
    private static SeacraftSouthSeaActivityConfig config;

    private static Map<Integer, SeacraftSouthSeaActivity> groupMap = new ConcurrentHashMap<>();


    @Override
    public boolean init() throws Exception {
        return true;
    }

    @Override
    public boolean reloadConfig() throws Exception {
        return true;
    }

    @Override
    public boolean reloadData() throws Exception {
        return true;
    }

    @Override
    public boolean stop() {
        return true;
    }

    public static void reloadActivityData() {
        getLogger().info("reload Seacraft SouthSea Activity start");
        List<ActivityInfo> openActivityInfoList = NormalActivityMgr.getOpenActivityInfoList(eActivityType.SeacraftActivity.getValue());
        if (openActivityInfoList.isEmpty()) {
            getLogger().info("no Seacraft SouthSea Activity in show time");
            activityInfo = null;
            config = null;
            groupMap.clear();
        } else {
            ActivityInfo tempActivityInfo = openActivityInfoList.get(0);
            List<Integer> activityIdList = new ArrayList<>();
            activityIdList.add(tempActivityInfo.getActivityId());
            Map<String, ActivityConfig> activityConfigMap = ActivityBussiness.getActivityConfigMap(activityIdList).get(tempActivityInfo.getActivityId());
            SeacraftSouthSeaActivityConfig southSeaActivityConfig = new SeacraftSouthSeaActivityConfig();
            southSeaActivityConfig.setShipList(SeacraftSouthSeaBusiness.getSeacraftSouthSeaShipConfigList(tempActivityInfo.getActivityId()));
            southSeaActivityConfig.setGuessList(SeacraftSouthSeaBusiness.getSeacraftSouthSeaGuessConfigList(tempActivityInfo.getActivityId()));
            southSeaActivityConfig.setFloorList(SeacraftSouthSeaBusiness.getSeacraftSouthSeaFloorConfigList(tempActivityInfo.getActivityId()));
            southSeaActivityConfig.setBattleList(SeacraftSouthSeaBusiness.getSeacraftSouthSeaBattleConfigList(tempActivityInfo.getActivityId()));
            southSeaActivityConfig.parseConfig(activityConfigMap);

            activityInfo = tempActivityInfo;
            config = southSeaActivityConfig;
        }
        for (GamePlayer gamePlayer : GamePlayerMgr.getAllOnlinePlayer()) {
            SeacraftSouthSeaModule southSeaModule = gamePlayer.getModule(SeacraftSouthSeaModule.class);
            southSeaModule.sendConfigToClient();
            southSeaModule.synUserData();
        }
        getLogger().info("reload Seacraft SouthSea Activity finish");
    }

    public static ActivityInfo getActivityInfo() {
        return activityInfo;
    }

    public static SeacraftSouthSeaActivityConfig getConfig() {
        return config;
    }

    public static SeacraftSouthSeaActivity initGroupActivity(int groupId) {
        SeacraftSouthSeaActivity activity = groupMap.get(groupId);
        if (null == activity) {
            synchronized (groupMap) {
                activity = groupMap.get(groupId);
                if (null == activity) {
                    activity = new SeacraftSouthSeaActivity(groupId, activityInfo.getActivityId());
                    groupMap.put(groupId, activity);
                }
            }
        }
        return activity;
    }

    public static SeacraftSouthSeaActivity getActivity(int groupId) {
        if (groupId != UnionActivityGroupHelper.NO_GROUP_ID) {
            initGroupActivity(groupId);
        }
        return groupMap.get(groupId);
    }

    public static SeacraftSouthSeaActivity getActivity(String unionId) {
        int groupId = GameUnionActivityGroupMgr.getGroupId(activityInfo.getActivityId(), unionId);
        if (groupId != UnionActivityGroupHelper.NO_GROUP_ID) {
            initGroupActivity(groupId);
        }
        return groupMap.get(groupId);
    }

    public static SeacraftSouthSeaActivity getActivity(long userId) {
        int groupId = GameUnionActivityGroupMgr.getGroupId(activityInfo.getActivityId(), userId);
        if (groupId != UnionActivityGroupHelper.NO_GROUP_ID) {
            initGroupActivity(groupId);
        }
        return groupMap.get(groupId);
    }

    /**
     * 是否玩家可以进入活动
     */
    public static int canEntryActivity(GamePlayer player, int activityId) {
        if (!ActivityMgr.activityInShowTime(getActivityInfo())) {
            return GameErrorCode.E_SEACRAFT_SOUTH_SEA_ACTIVITY_NO_OPEN;
        }
        if (!SystemOpenMgr.systemOpen(player, eSystemId.Seacraft.getValue())) {
            return GameErrorCode.E_SEACRAFT_SOUTH_SEA_ACTIVITY_NO_UNLOCK;
        }
        int groupId = GameUnionActivityGroupMgr.getGroupId(activityId, player.getUserId());
        if (null == getActivity(groupId)) {
            return GameErrorCode.E_SEACRAFT_SOUTH_SEA_ACTIVITY_NO_UNLOCK;
        }
        if (getActivityInfo() == null || getActivityInfo().getActivityId() != activityId) {
            return GameErrorCode.E_SEACRAFT_SOUTH_SEA_ACTIVITY_NO_OPEN;
        }
        return 0;
    }

    public static SeacraftSouthSeaProto.SyncSeacraftSouthSeaConfig.Builder builderSeacraftSouthSeaConfig(String language) {
        SeacraftSouthSeaProto.SyncSeacraftSouthSeaConfig.Builder builder = SeacraftSouthSeaProto.SyncSeacraftSouthSeaConfig.newBuilder();
        for (SeacraftSouthSeaShipConfig item : config.getShipList()) {
            SeacraftSouthSeaProto.SeacraftSouthSeaShipConfig.Builder shipConfig = SeacraftSouthSeaProto.SeacraftSouthSeaShipConfig.newBuilder();
            shipConfig.setLevel(item.getLevel());
            shipConfig.setExp(item.getExp());
            shipConfig.setSpeed(item.getSpeed());
            shipConfig.setHealth(item.getHealth());
            shipConfig.setBonus(item.getBonus());
            shipConfig.setShip(item.getShip());
            builder.addShipConfigList(shipConfig);
        }
        for (SeacraftSouthSeaGuessConfig item : config.getGuessList()) {
            SeacraftSouthSeaProto.SeacraftSouthSeaGuessConfig.Builder guessConfig = SeacraftSouthSeaProto.SeacraftSouthSeaGuessConfig.newBuilder();
            guessConfig.setId(item.getId());
            guessConfig.setRound(item.getRound());
            guessConfig.setCount(item.getCount());
            guessConfig.setDesc(ServerLanguageMgr.getContent(item.getDesc(), language));
            guessConfig.setAward(item.getAward());
            guessConfig.setShow(item.getShow());
            builder.addGuessConfigList(guessConfig);
        }

        for (SeacraftSouthSeaFloorConfig item : config.getFloorList()) {
            SeacraftSouthSeaProto.SeacraftSouthSeaFloorConfig.Builder floorConfig = SeacraftSouthSeaProto.SeacraftSouthSeaFloorConfig.newBuilder();
            floorConfig.setFloor(item.getFloor());
            floorConfig.setSpecialReward(item.getSpecialReward());
            floorConfig.setRewards(item.getRewards());
            floorConfig.setConsume(item.getConsume());
            builder.addFloorConfigList(floorConfig);
        }

        for (SeacraftSouthSeaBattleConfig item : config.getBattleList()) {
            SeacraftSouthSeaProto.SeacraftSouthSeaBattleConfig.Builder battleConfig = SeacraftSouthSeaProto.SeacraftSouthSeaBattleConfig.newBuilder();
            battleConfig.setId(item.getId());
            battleConfig.setRound(item.getRound());
            battleConfig.setType(item.getType());
            battleConfig.setVictoryTime(item.getVictoryTime());
            battleConfig.setRank(item.getRank());
            battleConfig.setAward(item.getAward());
            builder.addBattleConfigList(battleConfig);
        }

        return builder;
    }

    /**
     * 是否晋级
     *
     * @return
     */
    public static boolean isPromotion(String unionId) {
        SeacraftSouthSeaActivity activity = getActivity(unionId);
        if (null == activity) {
            return false;
        }
        return activity.isPromotion(unionId);
    }

    public static Map<Integer, List<String>> getRoundJoinUnionMap(int groupId) {
        SeacraftSouthSeaActivity activity = getActivity(groupId);
        if (null == activity) {
            return new ConcurrentHashMap<>();
        }
        return activity.getRoundJoinUnionMap();
    }

    /**
     * 获取各个 类型门客 门客集合 并按 赚钱 高到低 排序
     *
     * @param userId
     * @return
     */
    public static Map<Integer, List<UserPatrons>> getPatronsMap(long userId) {
        GamePlayer player = GamePlayerMgr.getOnlinePlayer(userId);
        Map<Integer, UserPatrons> patronsMap = null;
        if (player != null) {
            PatronsModule patronsModule = player.getModule(PatronsModule.class);
            patronsMap = patronsModule.getUserPatronsMap();
        } else {
            patronsMap = UserPatronsBussiness.getUserPatronsAndSkillMap(userId);
        }
        Map<Integer, List<UserPatrons>> patronMap = new HashMap<>();
        for (UserPatrons item : patronsMap.values()) {
            PatronsInfo patronsInfo = PatronsMgr.getPatronsInfoMap().get(item.getPatronsId());
            if (patronsInfo != null) {
                List<UserPatrons> list = patronMap.get(patronsInfo.getOccupation());
                if (list == null) {
                    list = new ArrayList<>();
                    patronMap.put(patronsInfo.getOccupation(), list);
                }
                list.add(item);
            }
        }
        // 排序
        patronMap.values().forEach(e -> {
            e.sort((t1, t2) -> {
                // 按战斗力排序
                return SeacraftSouthSeaCommonMgr.comparator(t1.getPatronsId(), t1.getAbility().longValue(), getAddPlus(t1), t2.getPatronsId(), t2.getAbility().longValue(), getAddPlus(t2));
            });
        });
        return patronMap;
    }

    public static void exit(GamePlayer player, SeacraftSouthSeaProto.SeacraftSouthSeaExitReqMsg reqMsg) {
        player.sendUnionActivityGroupPacket(CrossProtocol.C2_SEACRAFT_SOUTH_SEA_EXIT, reqMsg.toBuilder(), reqMsg.getActivityId());
    }

    public static void offLine(GamePlayer player) {
        if (!ActivityMgr.activityInShowTime(getActivityInfo())) {
            return;
        }
        if (!SystemOpenMgr.systemOpen(player, eSystemId.Seacraft.getValue())) {
            return;
        }
        SeacraftSouthSeaModule southSeaModule = player.getModule(SeacraftSouthSeaModule.class);
        if (southSeaModule.inActivity) {
            southSeaModule.inActivity = false;
            SeacraftSouthSeaProto.SeacraftSouthSeaExitReqMsg.Builder reqMsg = SeacraftSouthSeaProto.SeacraftSouthSeaExitReqMsg.newBuilder();
            reqMsg.setActivityId(activityInfo.getActivityId());
            exit(player, reqMsg.build());
        }
    }

    /**
     * @param patrons 要计算的当前门客
     * @return
     */
    public static SeacraftSouthSeaProto.SeacraftSouthSeaPatronsEntity.Builder builderSeacraftSouthSeaPatronsEntity(UserPatrons patrons) {
        int addPlus = 0;
        // 计算该门客的自己战斗加成
        addPlus = getAddPlus(patrons);

        SeacraftSouthSeaProto.SeacraftSouthSeaPatronsEntity.Builder builder = SeacraftSouthSeaProto.SeacraftSouthSeaPatronsEntity.newBuilder();
        builder.setPatronsId(patrons.getPatronsId());
        builder.setLevel(patrons.getLevel());
        builder.setStageLv(patrons.getStageLv());
        builder.setSkinId(patrons.getSkinId());
        builder.setEarn(patrons.getAbility().longValue());
        builder.setAddPlus(addPlus);
        builder.setPromotionId(patrons.getShowPromotionId());
        return builder;
    }

    public static int getAddPlus(UserPatrons patrons) {
        int addPlus = 0;
        if (patrons != null) {
            for (UserPatronsSkill userPatronsSkill : patrons.getSkillList()) {
                SkillInfo skillInfo = SkillMgr.getSkillInfo(userPatronsSkill.getSkillId());
                if (null == skillInfo){
                    continue;
                }
                if (skillInfo.getType() == eSkillType.BattleEffect.getValue()) {
                    addPlus += SkillMgr.getSkillAddition(skillInfo, userPatronsSkill.getSkillLv());
                }
            }
        }
        return addPlus;
    }

    /**
     * 向跨服索要晋级联盟的数据
     */
    public static synchronized void getPromotionUnionList() {
        if (!hasActivity()) {
            return;
        }
        for (SeacraftSouthSeaActivity activity : groupMap.values()) {
            activity.getPromotionUnionList(activityInfo, config);
        }
    }


    public static void synPatronsAbility(GamePlayer player, List<UserPatrons> patronsList) {
        if (patronsList == null) {
            return;
        }
        if (!hasActivity()) {
            return;
        }
        if (canEntryActivity(player, SeacraftSouthSeaMgr.getActivityInfo().getActivityId()) != 0) {
            return;
        }
        SeacraftSouthSeaActivity activity = getActivity(player.getUserId());
        if (null != activity) {
            activity.synPatronsAbility(player, patronsList);
        }
    }


    /**
     * 同步门客数据
     */
    public static void uploadObjectInfo() {
        for (SeacraftSouthSeaActivity activity : groupMap.values()) {
            activity.uploadObjectInfo();
        }
    }

    /**
     * 当前阶段是否能进出商会 或解散商会
     *
     * @param unionId
     * @return
     */
    public static boolean canInAndOutUnion(String unionId) {
        if (!hasActivity()) {
            return true;
        }

        SeacraftSouthSeaActivity activity = getActivity(unionId);
        if (null == activity) {
            return true;
        }
        return activity.canInAndOutUnion(unionId);
    }

    /**
     * 获取本轮晋级的联盟集合
     *
     * @return
     */
    public static List<String> getCurRoundPromotionUnionList() {
        if (!hasActivity()) {
            return null;
        }
        int curRound = SeacraftSouthSeaCommonMgr.getCurRound(SeacraftSouthSeaMgr.getActivityInfo(), SeacraftSouthSeaMgr.getConfig());
        if (curRound == 0 || curRound > SeacraftSouthSeaMgr.getConfig().roundTimeList.size()) {
            // 不在 海盗之乱结束- 南海丝路结束 区间
            return null;
        }
        List<String> resultList = new ArrayList<>();
        for (SeacraftSouthSeaActivity activity : groupMap.values()) {
            List<String> list = activity.getCurRoundPromotionUnionList();
            if (null != list) {
                resultList.addAll(list);
            }
        }
        return resultList;
    }


    /**
     * 尝试更新联盟会长信息
     */
    public static void attemptUpdateUnionMasterInfo(GamePlayer player) {
        if (player == null) {
            return;
        }
        try {
            String unionUid = player.getUserInfo().getUnionUid();
            if (StringUtils.isNullOrEmpty(unionUid)) {
                return;
            }
            UnionMember unionMember = CrossUnionMgr.getUnionMember(player.getUserId());
            CrossUnionInfo unionInfo = CrossUnionMgr.getUnionInfo(unionUid);
            if (unionMember != null && unionMember.getPosition() == eUnionPosition.Master.getValue()) {
                //如果是会长，会长信息也要更新下
                synUnionInfo(1, unionUid, 0, unionInfo);
            }
        } catch (Exception e) {
            getLogger().error(e.getMessage(), e);
        }
    }

    /**
     * 同步联盟信息
     *
     * @param type
     * @param unionId
     * @param userId
     * @param unionInfo
     */
    public static void synUnionInfo(int type, String unionId, long userId, UnionInfo unionInfo) {
        if (!hasActivity()) {
            return;
        }
        SeacraftSouthSeaActivity activity = getActivity(unionId);
        if (null != activity) {
            activity.synUnionInfo(activityInfo, config, type, unionId, userId, unionInfo);
        }
    }


    public static boolean hasActivity() {
        if (activityInfo == null || config == null) {
            return false;
        }
        return true;
    }
}
